package com.v1.video.activity;

import java.util.ArrayList;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.v1.video.R;
import com.v1.video.domain.HotAndMyThemePageInfo;
import com.v1.video.domain.HotThemePageInfo;
import com.v1.video.domain.HotThemePageObj;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ThemeInfo;
import com.v1.video.option.util.SearchAboutUtil;
import com.v1.video.util.Utils;

/**
 * 选择话题类
 * @author fengtao
 *
 */
public class SelectThemeActivity extends BaseActivity {

	private final String TAG = "SelectThemeActivity";
	private LayoutInflater mInflater;
	private View mCancel;
	private View mConfirm;
	private GridView mGV;
	private MyAdapter mAdapter;
	private int mCurSelIndex = -1;
	private String mCurName = "";
//	MultiAutoCompleteTextView autoText = null;
	EditText autoText = null;
	private ThemeSearchAdapter adapterSearchTheme;
	
	private ArrayList<ThemeInfo> listThemeSearch = new ArrayList<ThemeInfo>();
	private ArrayList<ThemeInfo> listThemeSearchResult = new ArrayList<ThemeInfo>();
	private ArrayList<ThemeInfo> listTheme = new ArrayList<ThemeInfo>();
	private ListView listViewSearch = null;
	private final int pageSize = 20;
	@Override
	protected void onCreate(Bundle inState) {
		super.onCreate(inState);
		mInflater = this.getLayoutInflater();
		setContentView(R.layout.activity_select_theme_lay);
		Bundle bundle = this.getIntent().getExtras();
		if(bundle != null && bundle.containsKey("data")){
			mCurName=bundle.getString("data").split("\\|")[0];
		}
	}

	@Override
	protected void initView() {
		mCancel = findViewById(R.id.tv_cancel);
		mConfirm = findViewById(R.id.tv_confirm);
		((TextView) findViewById(R.id.tv_caption)).setText(this.getResources()
				.getString(R.string.share_add_theme));
		findViewById(R.id.iv_back).setVisibility(View.GONE);
		findViewById(R.id.tv_title);
		mCancel.setVisibility(View.VISIBLE);
		mConfirm.setVisibility(View.VISIBLE);
		
		mGV = (GridView) findViewById(R.id.gridView1);
		
		autoText = (EditText)findViewById(R.id.theme_auto_text);
		listViewSearch = (ListView)findViewById(R.id.theme_listview);
//		for(int i = 0; i < 20;i++){
//			ThemeInfo info = new ThemeInfo();
//			info.setAname("切一个"+i);
//			listThemeSearch.add(info);
//		}
//		for(int i = 0; i < 20;i++){
//			ThemeInfo info = new ThemeInfo();
//			info.setAname("香蕉"+i);
//			listThemeSearch.add(info);
//		}
//		for(int i = 0; i < 20;i++){
//			ThemeInfo info = new ThemeInfo();
//			info.setAname("桔子"+i);
//			listThemeSearch.add(info);
//		}
		
	}

	@Override
	protected void initData() {
		mAdapter = new MyAdapter();
		mGV.setAdapter(mAdapter);
		autoText.addTextChangedListener(watcher);
		adapterSearchTheme = new ThemeSearchAdapter();
		listViewSearch.setAdapter(adapterSearchTheme);
//		autoText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(length)});       
////		adapterSearchTheme = new ThemeSearchAdapter(SelectThemeActivity.this,R.layout.item_select_theme_search_lay,listThemeSearch);
////		autoText.setAdapter(adapterSearchTheme);
//		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
//                R.layout.item_select_theme_search_lay, catalogs);
//		autoText.setAdapter(adapter1);
//		autoText.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
//		ArrayAdapter<String> 
		new GetDataAsync().execute();
	}

	@Override
	protected void setListener() {
		mCancel.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				back();
			}});
		
		mConfirm.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(mCurSelIndex!=-1){
					Intent intent=new Intent();
//					intent.putExtra("data", catalogs[mCurSelIndex]+"|ID");
					if(autoText.getText().toString().length() > 0){
						intent.putExtra("data", autoText.getText().toString());
					}else{
						intent.putExtra("data", listTheme.get(mCurSelIndex).getName());
					}
					setResult(RESULT_OK,intent);
					finish();
				}else{
					
					if(autoText.getText().toString().length() > 0){
						Intent intent=new Intent();
						intent.putExtra("data", autoText.getText().toString());
						setResult(RESULT_OK,intent);
						finish();
					}else{
						finish();
					}
				}
			}});
		
		autoText.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER) {
					 String keyword = autoText.getText().toString();
					 mGV.setVisibility(View.GONE);
					 new GetSearchDataAsync(keyword).execute();
				}
				return false;
			}
		});
		
		this.findViewById(R.id.iv_search).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String keyword = autoText.getText().toString();
				mGV.setVisibility(View.GONE);
				if(!TextUtils.isEmpty(keyword)){
					 new GetSearchDataAsync(keyword).execute();
				}
			}
		});

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			back();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void back() {
		setResult(RESULT_CANCELED, new Intent());
		finish();
	}
	
	private class MyAdapter extends BaseAdapter{

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listTheme.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return listTheme.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			PlaceHolder holder = null;
			final ThemeInfo themeInfo = listTheme.get(position);
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.item_select_theme_lay, null);
				holder = new PlaceHolder();
				holder.txt = (TextView) convertView.findViewById(R.id.textView1);
				holder.imageView1 = (ImageView)convertView.findViewById(R.id.imageView1);
				convertView.setTag(holder);
			}else{
				holder = (PlaceHolder) convertView.getTag();
			}
			
			holder.txt.setText("#"+themeInfo.getName()+"#");
			if(mCurSelIndex == -1 && mCurName.equals(themeInfo.getName())){
				mCurSelIndex = position;
			}
			if(position == mCurSelIndex){
				holder.txt.setBackgroundResource(R.drawable.shape_topic_pressed);
				holder.imageView1.setVisibility(View.VISIBLE);
			}else{
				holder.txt.setBackgroundResource(R.drawable.select_topic_selector);
				holder.imageView1.setVisibility(View.GONE);
			}
			holder.txt.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					mCurSelIndex = position;
					MyAdapter.this.notifyDataSetChanged();
				}});
			
			return convertView;
		}
		
		private class PlaceHolder{
			TextView txt;
			ImageView imageView1;
		}
		
	}
		
	
	private class ThemeSearchAdapter extends BaseAdapter{

		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return listThemeSearchResult.size();
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return listThemeSearchResult.get(arg0);
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			PlaceHolder holder = null;
			final ThemeInfo themeInfo = listThemeSearchResult.get(position);
			if(convertView == null){
				convertView = mInflater.inflate(R.layout.item_select_theme_search_lay, null);
				holder = new PlaceHolder();
				holder.txt = (TextView) convertView.findViewById(R.id.textView1);
				holder.imageView1 = (ImageView)convertView.findViewById(R.id.imageView1);
				convertView.setTag(holder);
			}else{
				holder = (PlaceHolder) convertView.getTag();
			}
			
			holder.txt.setText(themeInfo.getName());
			convertView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Intent intent=new Intent();
					intent.putExtra("data", listThemeSearchResult.get(position).getName());
					setResult(RESULT_OK,intent);
					finish();
				}
			});
			return convertView;
		}
		
		private class PlaceHolder{
			TextView txt;
			ImageView imageView1;
		}

		
		
	}
	int m = 0;
	 private TextWatcher watcher = new TextWatcher(){

	        @Override
	        public void afterTextChanged(Editable s) {
	            // TODO Auto-generated method stub
	            
	        }

	        @Override
	        public void beforeTextChanged(CharSequence s, int start, int count,
	                int after) {
	            // TODO Auto-generated method stub
	            
	        }

	        @Override
	        public void onTextChanged(CharSequence s, int start, int before,
	                int count) {
	            int strLength = autoText.getText().toString().length();
	            String keyword = autoText.getText().toString();
	            if(strLength <= 0){
	            	listViewSearch.setVisibility(View.GONE);
	            }else{
	            	//listViewSearch.setVisibility(View.VISIBLE);
	            }
	            //new GetSearchDataAsync(keyword).execute();
//	            listThemeSearchResult.clear();
//	            for(int i = 0; i < listThemeSearch.size();i++){
//	            	if(listThemeSearch.get(i).getName().contains(keyword)){
//	            		listThemeSearchResult.add(listThemeSearch.get(i));
//	            	}
//	            }
////	            if(m >= listThemeSearch.size()-10){
////	            	m = 0;
////	            }
////	            for(int i = m;i<m+10;i++){
////	            	listThemeSearchResult.add(listThemeSearch.get(i));
////	            }
////	            m+=10;
//	            
//	            adapterSearchTheme.notifyDataSetChanged();
	        }        
	    };

	    
	    /**
	     * 获取推荐话题
	     */
	    private class GetDataAsync extends AsyncTask<Void, Void, Boolean> {
	        
	        private String errorMsg = "";
	        
	        private ProgressDialog pd;
	        private HotAndMyThemePageInfo themePageInfo;
	        private int pageIndex;
	        public GetDataAsync(int pageIndex) {
	        	this.pageIndex = pageIndex;
	        }
	        
	        public GetDataAsync() {
	        }
	        @Override
	        protected void onPreExecute() {
	            super.onPreExecute();
	            pd = Utils.getProgressDialog(SelectThemeActivity.this,getResources().getString(R.string.get_data), this);
	            pd.show();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Void... params) {
	            try {
	            	SearchAboutUtil search = new SearchAboutUtil();
	            	String userId = "";
	            	if(LoginInfo.getInstance().isLogin()){
	            		userId = LoginInfo.getInstance().getUserId();
	            	}
	            	themePageInfo = search.getHotThemeAndMyByFabu(userId);
	            } catch (Exception e) {
	                e.printStackTrace();
	                errorMsg = e.getMessage();
	            }
	            return false;
	            
	        }
//	        Uri uri = Uri.parse(versionInfo.url); 
//	        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//	        startActivity(it);
	        @Override
	        protected void onPostExecute(Boolean result) {
	            super.onPostExecute(result);
	            if(pd != null && pd.isShowing()){
	                pd.cancel();
	            }            
	            if (errorMsg.equals("")) {
	            	if(themePageInfo != null){
						if(themePageInfo.getObj() != null){
							HotThemePageObj obj = themePageInfo.getObj();
							if(obj.getMyTopicList() != null){
								listThemeSearch.addAll(obj.getMyTopicList());
							}
							if(obj.getHotTopicList() != null){
								listThemeSearch.addAll(obj.getHotTopicList());
							}
							
							if(listThemeSearch.size() <= pageSize){
								listTheme.addAll(listThemeSearch);
							}else{
								for(int i = 0; i < pageSize;i++){
									listTheme.add(listThemeSearch.get(i));
								}
							}
							mAdapter.notifyDataSetChanged();
						}else{
							ToastAlone
							.showToast(SelectThemeActivity.this, themePageInfo.getMsg(), 1);
						}
					}else{
						ToastAlone
						.showToast(SelectThemeActivity.this, "未知错误", 1);
					}
	            } else {
	                ToastAlone.showToast(SelectThemeActivity.this, errorMsg, 1);
	            }
	        }
	    }
	    
	    /**
	     * 获取推荐话题
	     */
	    private class GetSearchDataAsync extends AsyncTask<Void, Void, Boolean> {
	        
	        private String errorMsg = "";
	        
	        private ProgressDialog pd;
	        private HotThemePageInfo themePageInfo;
	        private int pageIndex;
	        String keyword = "";
	        public GetSearchDataAsync(String name) {                        
	        	this.keyword = name;
	        }
	        
	        public GetSearchDataAsync() {
	        }
	        @Override
	        protected void onPreExecute() {
	            super.onPreExecute();
	            pd = Utils.getProgressDialog(SelectThemeActivity.this,getResources().getString(R.string.get_data), this);
	            pd.show();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Void... params) {
	            try {
	            	SearchAboutUtil search = new SearchAboutUtil();
	            	themePageInfo = search.getThemeBySearchWithFabu(keyword);
	            } catch (Exception e) {
	                e.printStackTrace();
	                errorMsg = e.getMessage();
	            }
	            return false;
	            
	        }
//	        Uri uri = Uri.parse(versionInfo.url); 
//	        Intent it   = new Intent(Intent.ACTION_VIEW,uri); 
//	        startActivity(it);
	        @Override
	        protected void onPostExecute(Boolean result) {
	            super.onPostExecute(result);
	            if(pd != null && pd.isShowing()){
	                pd.cancel();
	            }            
	            if (errorMsg.equals("")) {
	            	if(themePageInfo != null){
						if(themePageInfo.getObj() != null){
							listViewSearch.setVisibility(View.VISIBLE);
							listThemeSearchResult.clear();
							listThemeSearchResult.addAll(themePageInfo.getObj());
							adapterSearchTheme.notifyDataSetChanged();
						}else{
							listViewSearch.setVisibility(View.GONE);
							ToastAlone
							.showToast(SelectThemeActivity.this, themePageInfo.getMsg(), 1);
						}
					}else{
						listViewSearch.setVisibility(View.GONE);
						ToastAlone
						.showToast(SelectThemeActivity.this, "未知错误", 1);
					}
	            } else {
	            	listViewSearch.setVisibility(View.GONE);
	                ToastAlone.showToast(SelectThemeActivity.this, errorMsg, 1);
	            }
	        }
	    }
}
